var localVars = new Array();

var Utils = {
		checkMail:function (email){
      var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
      if (filter.test(email)) {
      	return true;
      }
      return false;
    },
    inAdvanceLoadingIMGS:function(url,fn){
        /*加載指定的圖片 注意 url可以字符串 也可以是 一個圖片的url數組
         fn在所有圖片加載完後進行的囘調(無論，成功 失敗 全算加載成功)
         fn(oklist,errlist)   oklist表示一個加載成功的url列表 errlist表示加載失敗的列表
         */
        if(typeof url=='string'){
            url=[url];
        }

        var oklist=[];
        var errlist=[];

        for(var i=0;i<url.length;i++){
            var img=new Image();
            img.src=url[i];
            img.onload=ok;
            img.onerror=err;
        }

        function ok(){
            oklist.push(this.src);
            checkLoad();
        }
        function err(){
            errlist.push(this.src);
            checkLoad();
        }
        function checkLoad(){
            if((oklist.length + errlist.length) >= url.length ){
                if(typeof fn=='function'){
                    fn(oklist,errlist);
                }
            }
        }
    },
		replaceInput: function(obj, newT){
			//var obj = document.getElementById("id");
			var newO=document.createElement('input');
			newO.setAttribute('type',newT);
			newO.setAttribute('name',obj.getAttribute('name'));
			newO.setAttribute('id',obj.getAttribute('id'));
			newO.setAttribute('class',obj.getAttribute('class'));
			newO.setAttribute('style',obj.getAttribute('style'));
			//newO.setAttribute('value',obj.getAttribute('value'));
			obj.parentNode.replaceChild(newO,obj);
			//newO.focus();
		},
    jsonToString: function (obj) {
        var THIS = this;
        switch (typeof (obj)) {
            case 'string':
                return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
            case 'array':
                return '[' + obj.map(THIS.jsonToString).join(',') + ']';
            case 'object':
                if (obj instanceof Array) {
                    var strArr = [];
                    var len = obj.length;
                    for (var i = 0; i < len; i++) {
                        strArr.push(THIS.jsonToString(obj[i]));
                    }
                    return '[' + strArr.join(',') + ']';
                } else if (obj == null) {
                    return 'null';

                } else {
                    var string = [];
                    for (var property in obj) string.push(THIS.jsonToString(property) + ':' + THIS.jsonToString(obj[property]));
                    return '{' + string.join(',') + '}';
                }
            case 'number':
                return obj;
            case false:
                return obj;
        }
    },
    stringToJSON: function (obj) {
    	return eval('(' + obj + ')');
    },
    hasLocalStorage: function (obj) {
        try {
            if (typeof (localStorage) == 'undefined' || !window.localStorage) {
                return false;
            }
        } catch (e) {
            return false;
        }
        return true;
    },
    hasSessionStorage: function (obj) {
        try {
            if (typeof (sessionStorage) == 'undefined' || !window.sessionStorage) {
                return false;
            }
        } catch (e) {
            return false;
        }
        return true;
    },
    hasStorage: function (obj) {
        try {
            if (typeof (sessionStorage) == 'undefined' || typeof (localStorage) == 'undefined' || !window.localStorage || !window.sessionStorage) {
                return false;
            }
        } catch (e) {
			//alert(e);
            return false;
        }
        return true;
    },
    isNoStorage: false,
    setCookie: function (name, value, days) {
		try {
        //test environment
        value = this.jsonToString(value);
        var exp = new Date();
        exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
        document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
		}catch (e) {}
		return false;
    },
    _setLocal: function (name, value, days) {
        value = this.jsonToString(value);
        localStorage.removeItem(name);
        localStorage.setItem(name, value);
    },
    _setNoStorage: function (name, value, days) {
        localVars[name]=value;
    },
    getCookie: function (name) {
        //test environment	
        try {
            var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
		        if (arr != null)
		            return this.stringToJSON(unescape(arr[2]));
		}catch (e) {}
        
        return null;
    },
    _getLocal: function (name) {
		try {
			var result = localStorage.getItem(name);
			if (result) return this.stringToJSON(result);
		}catch (e) {}
        return null;
    },
    _getNoStorage: function (name) {
    	return localVars[name];
    },
    delCookie: function (name) {
        //test environment
        var exp = new Date();
        exp.setTime(exp.getTime() - 60000);
        document.cookie = name + "=;expires=" + exp.toGMTString();
        return false;
    },
    _delLocal: function (name) {
        localStorage.removeItem(name);
    },
    _delNoStorage: function (name) {
    		localVars[name]=null;
    },
    validateStorage: function() {
    	var keyinfo = this.getCookie("key");
      if (keyinfo != null) {
      	if(typeof (keyinfo.user) == 'undefined' || typeof (keyinfo.server) == 'undefined' || typeof (keyinfo.key) == 'undefined' || typeof (keyinfo.referer) == 'undefined' || typeof (keyinfo.refercode) == 'undefined')
      	{
      		//bad version
      		this.delCookie("key");
      	}
      }
    },
    timeString2: function (seconds) {
    		var days = parseInt(seconds / 86400);
    		if(days > 0)
    		{
    			return days + "+ days";
    		}
        return this.timeString(seconds);
    },
    timeString: function (seconds) {
        var hours = parseInt(seconds / 3600);
        var mins = parseInt((seconds % 3600) / 60);
        var secs = seconds % 60;
        return this.timeStr(hours, mins, secs);
    },
    timeStr: function (hours, mins, secs) {
        var disp;
        if (hours <= 9) {
            disp = "0";
        } else {
            disp = "";
        }
        disp += hours + ":";
        if (mins <= 9) {
            disp += "0" + mins + ":";
        } else {
            disp += mins + ":";
        }
        if (secs <= 9) {
            disp += "0" + secs;
        } else {
            disp += secs;
        }
        return (disp);
    },
	ftime: function(dt, format){
		/*
		* eg:format="yyyy-MM-dd hh:mm:ss";
		*/
		var o = {
			"M+" :  dt.getMonth()+1,  //month
			"d+" :  dt.getDate(),     //day
			"h+" :  dt.getHours(),    //hour
			"m+" :  dt.getMinutes(),  //minute
			"s+" :  dt.getSeconds(), //second
			"q+" :  Math.floor((dt.getMonth()+3)/3),  //quarter
			"S"  :  dt.getMilliseconds() //millisecond
		}

		if(/(y+)/.test(format)) {
			format = format.replace(RegExp.$1, (dt.getFullYear()+"").substr(4 - RegExp.$1.length));
		}

		for(var k in o) {
			if(new RegExp("("+ k +")").test(format)) {
				format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
			}
		}
		return format;
	},
    addCss: function (cssid, cssurl) {
		var d = document;
		var dHead = d.getElementsByTagName('head')[0];
		var newStyle = d.createElement('link');
		newStyle.setAttribute('rel','stylesheet');
		newStyle.setAttribute('type','text/css');
		newStyle.setAttribute('href',cssurl);
		newStyle.setAttribute('id',cssid);
		dHead.appendChild(newStyle);
    },
    removeCss: function (cssid) {
    	var d = document;
     	var dHead = d.getElementsByTagName('head')[0];
     	var newStyle = d.getElementById(cssid);
     	if(newStyle != null)
     	{
     		dHead.removeChild(newStyle);
     	}
    },
    loadImage: function(div, imgsrc) {
    	var img = new Image();
		img.onload= function(){div.css('background-image', 'url('+ imgsrc +')');};
		img.src = imgsrc;
		//img.onerror = function(){div.css("background-image", "url("+samplesrc+")");};
    },
    loadImage2: function(imgblock, imgsrc) {
    	var img = new Image();
		img.onload= function(){imgblock.attr('src',imgsrc);};
		img.src = imgsrc;
		//img.onerror = function(){div.css("background-image", "url("+samplesrc+")");};
    },
    trim: function(str) { 
			return str.replace(/(^\s*)|(\s*$)/g, ""); 
	},
	QueryString : function(item){
		var svalue = location.search.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)","i"));
		return svalue ? svalue[1] : svalue;
	},
	QueryString2Cookie: function(){
		hu = window.location.search.substring(1);
		if(hu!=null && hu!='')
		{
			gy = hu.split("&");
			for (i=0;i<gy.length;i++) {
				ft = gy[i].split("=");
				if(typeof(ft[1]) != 'undefined' && ft[1] != null && ft[1] != '')
				{
					var result = unescape(ft[1]);
					this.setCookie(ft[0],this.stringToJSON(result));
				}
			}
		}
	},
	parseInt: function(v, def) {
		var r = parseInt(v);
		return isNaN(r)? def : r;
	},
	fade:function(obj, opacity, speed, completeObj) {
		for(var i=0; i<obj.length; i++)
		{
			opacity[i] += speed[i];
			if(opacity[i] <= 0)
			{
				opacity[i] = 0;
			}
			else if(opacity[i] >= 1)
			{
				opacity[i] = 1;
			}
			obj[i].css("opacity",opacity[i]);
			if(opacity[i] == 0 || opacity[i] == 1)
			{
				obj.splice(i, 1); 
				opacity.splice(i, 1);
				speed.splice(i, 1);
				i--;
			}
		}
		if(obj.length == 0)
		{
			if(completeObj)
			{
				completeObj.play();
			}
		}
		else
		{
			setTimeout(function(){Utils.fade(obj, opacity, speed, completeObj);}, 100);
		}
	},
	bounce:function(obj, pos, speed, ulimit, dlimit, isback, completeObj) {
		for(var i=0; i<obj.length; i++)
		{
			pos[i]+=speed[i];
			if(ulimit[i] >= pos[i])
			{
				pos[i] = ulimit[i];
			}
			else if(dlimit[i] <= pos[i])
			{
				pos[i] = dlimit[i];
			}
			//Debug.trace("bounce:"+pos[i]);
			obj[i].css("top",pos[i]);
			if(ulimit[i] >= pos[i] || dlimit[i] <= pos[i])
			{
				if(isback[i])
				{
					obj.splice(i, 1); 
					pos.splice(i, 1);
					speed.splice(i, 1);
					ulimit.splice(i, 1);
					dlimit.splice(i, 1);
					isback.splice(i, 1);
					i--;
				}
				else
				{
					speed[i] = -speed[i];
					isback[i] = true;
				}
			}
		}
		if(obj.length == 0)
		{
			if(completeObj)
			{
				completeObj.play();
			}
		}
		else
		{
			setTimeout(function(){Utils.bounce(obj, pos, speed, ulimit, dlimit, isback, completeObj);}, 100);
		}
	},
	idle:function(milisecs, completeObj) {
		//Debug.trace(milisecs);
		setTimeout(function(){completeObj.play();}, milisecs);
	},
	animate:function(obj, animation, completeObj) {
		obj.setAnimation(animation, function(){
			//Debug.trace("animate done");
			obj.hide();
			if(completeObj)
			{
				completeObj.play();
			}
		});
	},
	wait2toggle:function(milisecs, obj, completeObj) {
		setTimeout(function(){
			for(var i=0; i<obj.length; i++)
			{
				obj[i].toggle();
			}
			if(completeObj)
			{
				completeObj.play();
			}
		}, milisecs);
	},
	toggle:function(obj, count, completeObj) {
		for(var i=0; i<obj.length; i++)
		{
			obj[i].toggle();
			if(count[i] <= 0)
			{
				obj[i].show();
				obj.splice(i, 1); 
				count.splice(i, 1);
				i--;
			}
			else
			{
				count[i]--;
			}
		}
		if(obj.length == 0)
		{
			if(completeObj)
			{
				completeObj.play();
			}
		}
		else
		{
			setTimeout(function(){Utils.toggle(obj, count, completeObj);}, 100);
		}
	},
	/* 准备一个或者多个数据, 对于多数据请求特别有用！
	 * fnPrepare: 回调， 参数(params, notify),请在准备完成后调用notify,准备好的数据如果是局部的话请放在params中
	 * fnCheck: 回调， 参数(params) 执行检查params中的数据是否准备完毕
	 * fnNotify: 回调，fnCheck返回成功的时候被调用
	 * loadingPanel: 如果设置为一个id例如#loading，则会在未完成时候始终显示#loading ,或者 $('#loading')
	 * 示例:
			var a;
			var b;
			Utils.prepare(
				function(notify) {
					ajaxCall(
						...
						,
						function(result){
							a = result;
						}
						,
						notify
						,...
					);
					ajaxCall(
						...
						,
						function(result){
							b = result;
						}
						,
						notify
						,...
					);
				},
				function() {
					return a != null && b != null;
				},
				function() {
					//so some real thing
				},'#loading'
			);
	 */
	prepare: function(fnPrepare,fnCheck,fnNotify,loadingPanel){
		var loading = $(loadingPanel);
		function notify(){
			if(fnCheck()) {
				fnNotify();
				if(loadingPanel) loading.hide();
				return true;
			} else if(loadingPanel){
				loading.show();
				return false;
			}
		}
		fnPrepare(notify);
		notify();
	}

};

(function (cls) {
	var isIphone = (/iphone/gi).test(navigator.appVersion),
	isIpad = (/ipad/gi).test(navigator.appVersion),
	isAndroid = (/android/gi).test(navigator.appVersion),
	isTouch = isIphone || isIpad || isAndroid;
	window.isIphone = isIphone;
    window.isAndroid = isAndroid;
	// Handle event binding
	
	if(isTouch){
		jQuery.fn['touch'] = function (fn) {
			return fn ? this.bind('touchend', fn) : this.trigger('touchend');
		};

		if (jQuery.attrFn) {
			jQuery.attrFn['touch'] = true;
		}
	} else {
		jQuery.fn['touch'] = function (fn) {
			return fn ? this.bind('click', fn) : this.trigger('click');
		};

		if (jQuery.attrFn) {
			jQuery.attrFn['touch'] = true;
		}
	}

    var hasLocal = cls.hasStorage();

    if (hasLocal) {
        cls.setCookie = cls._setLocal;
        cls.getCookie = cls._getLocal;
        cls.delCookie = cls._delLocal;
    }
    else if (isIphone || isIpad)
    {
    	cls.setCookie = cls._setNoStorage;
    	cls.getCookie = cls._getNoStorage;
    	cls.delCookie = cls._delNoStorage;
    	cls.isNoStorage = true;
    }
    	
    if(window.JSON){
        cls.jsonToString = window.JSON.stringify;
        cls.stringToJSON = window.JSON.parse;
    }
})(Utils);
